﻿
using ShapeManager;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using UserControls;

namespace Tools
{
    public class ToolPolygon : ToolObject
    {
        public ToolPolygon()
        {


            try { 
                Cursor = new Cursor("cursor/Pencil.cur"); 
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                Debug.WriteLine(ex.Message);
            }
            
        }

        private int lastX;
        private int lastY;
        private UPolygon newPolygon;
        private const int minDistance = 15 * 15;

        /// <summary>
        /// Left mouse button is pressed
        /// </summary>
        /// <param name="drawArea"></param>
        /// <param name="e"></param>
        public override void OnMouseDown(UImageWindow uImageWindow, MouseEventArgs e)
        {
            // Create new polygon, add it to the list
            // and keep reference to it
            newPolygon = new UPolygon(e.X, e.Y, e.X + 1, e.Y + 1);
            AddNewObject(uImageWindow, newPolygon);
            lastX = e.X;
            lastY = e.Y;
        }

        /// <summary>
        /// Mouse move - resize new polygon
        /// </summary>
        /// <param name="drawArea"></param>
        /// <param name="e"></param>
        public override void OnMouseMove(UImageWindow uImageWindow, MouseEventArgs e)
        {
            try { uImageWindow.Cursor = Cursor; }
            catch (Exception ex)
            {
                uImageWindow.Cursor = Cursors.Default;
                Debug.WriteLine(ex.Message);
            }

            if (e.Button != MouseButtons.Left)
                return;

            if (newPolygon == null)
                return;                 // precaution

            Point point = new Point(e.X, e.Y);
            int distance = (e.X - lastX) * (e.X - lastX) + (e.Y - lastY) * (e.Y - lastY);

            if (distance < minDistance)
            {
                // Distance between last two points is less than minimum -
                // move last point
                newPolygon.MoveHandleTo(point, newPolygon.HandleCount);
            }
            else
            {
                // Add new point
                newPolygon.AddPoint(point);
                lastX = e.X;
                lastY = e.Y;
            }
            uImageWindow.Refresh();
        }

        public override void OnMouseUp(UImageWindow uImageWindow, MouseEventArgs e)
        {
            newPolygon = null;
            base.OnMouseUp(uImageWindow, e);
        }


    }
}
